class Exer04
{
	public static void main(String[] args) 
	{
		int[] a = {2,8,5,1,6};	
		System.out.println("排序前：");
		printArray(a);
		
		System.out.println("排序后：");	
		bubbleSort(a);
		printArray(a);

		System.out.println("所在的位置是：");	
		System.out.println(binarySearch(a, 8));
	}
	/**
	 *	 冒泡排序
	 */
	public static void bubbleSort(int[] array) 
	{	 
		int temp ;
		for (int i = 0;i<array.length-1 ;i++ )
		{	
			for (int j = 0;j < array.length-1-i ; j++)
			{			
				if (array[j]>array[j+1])
				{
					temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}

	/**
	 *	 二分法查找，找到返回其索引值，未找到返回-1
	 *	 @param array
	 *	 @param key
	 */
	public static int binarySearch(int[] array ,int key)
	{
		int low = 0;
		int high = array.length-1;
		int mid;
		while(low<=high)
		{
			mid = (low+high)/2;
			if (key<array[mid])
				high = mid -1;
			else if (key >array[mid])
				low = mid +1;
			else 
				return mid;
		}
		return -1;
	}
	/**
	 *	 打印数组
	 *	 @param array
	 */
	public static void printArray(int[] array)
	{
	   	for (int index: array)
		{
			System.out.print(index+"\t");
		}
		System.out.println();	
	}
}
